package com.xykj.enterprise.wechat.busi.api.identity;

import com.alibaba.fastjson.JSONArray;
import com.xykj.enterprise.wechat.bean.busi.WeComEnterpriseAuthUrl;
import com.xykj.enterprise.wechat.bean.ext.identity.PreAuthCode;
import com.xykj.enterprise.wechat.busi.config.ExtClient;
import com.xykj.enterprise.wechat.busi.service.sys.SysParamService;
import com.xykj.enterprise.wechat.busi.service.identity.SuiteTicketService;
import com.xykj.enterprise.wechat.util.Const;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhouxu
 * @create 2021-03-29 21:40
 */
@Function(description = "生成企业微信-企业授权地址", parameters = {
        @Parameter(name = "suite_id", type = Type.String, description = "以ww或wx开头应用id（对应于旧的以tj开头的套件id", required = true),
        @Parameter(name = "redirectUri", type = Type.String, description = "授权通过后回调url", required = true),
        @Parameter(name = "state", type = Type.String, description = "state", required = true),
        @Parameter(name = "secret", type = Type.String, description = "secret", required = true),

})
@Component
@Slf4j
public class GenerateWeComEnterpriseAuthUrl implements Action {

    @Autowired
    private SuiteTicketService suiteTicketService;
    @Autowired
    private ExtClient extClient;

    @Override
    public Response execute(Request request) throws Exception {
        String suiteId = request.getString("suite_id");
        String redirectUri = request.getString("redirectUri");
        String state = request.getString("state");
        try {
            Map params = new HashMap();
            params.put("suite_id", suiteId);
            params.put("suite_secret", request.getString("secret"));
            params.put("suite_ticket", suiteTicketService.getLatest(suiteId).getSuitTicket());

            // 获取预授权码
            PreAuthCode preAuthCode = extClient.get("GetPreAuthCode", params, PreAuthCode.class);
            // 生成企业授权地址
            WeComEnterpriseAuthUrl url = new WeComEnterpriseAuthUrl(preAuthCode.getPre_auth_code(), suiteId, redirectUri, state);
            log.debug("url json string : {}", JSONArray.toJSON(url).toString());
            return Response.success().put("data", url);

        } catch (Exception e) {
            log.error("生成企业微信-企业授权地址失败", e);
            return Response.fail(e);
        }

    }
}
